const nedb = require('nedb')
const log = console.log

// const database = new lokijs('./db/parkings.db', {
//     autosave: true,
//     autosaveInterval: 6000,
// })
// database.loadDatabase({}, err => err)

// const database = new nedb({ filename: "./db/parkings.db" })
// database.loadDatabase((err) => { log("加载数据库失败！") })


class ParkingDB {
    constructor(dbname) {
        this.db = new nedb({ filename: dbname, autoload: true })
    }

    insert(obj) {
        return new Promise((rs, rj) => {
            this.db.insert(obj, (err) => {
                if (err)
                    rj(err)
                else
                    rs(true)
            })
        })
    }

    find(obj = {}) {
        return new Promise((rs, rj) => {
            this.db.find(obj, (err, docs) => {
                if (err || !docs)
                    rj()
                else
                    rs(docs)
            })
        })
    }

    findOne(obj) {
        return new Promise((rs, rj) => {
            this.db.findOne(obj, (err, doc) => {
                if (err || !doc)
                    rj()
                else
                    rs(doc)
            })
        })
    }

    update(query, uval, opts) {
        return new Promise((rs, rj) => {
            this.db.update(query, uval, opts, (err, numberOfUpdated, upsert) => {
                if (err)
                    rj(err)
                else
                    rs(true)
            })
        })
    }

    remove(query, options) {
        return new Promise((rs, rj) => {
            this.db.remove(query, options, (err, n) => {
                if (err)
                    rj(err)
                else
                    rs(n)
            })
        })
    }
}

export default ParkingDB